import { asyncRoutes, constantRoutes } from '@/router'
// api接口
import { getRoles, getPermissions } from '@/api/roles'

// 转换路由
import { generateRoutes } from '@/utils/index'


const state = {
  routes: [],
  addRoutes: [],
  permission: [],//权限
}

const mutations = {
  // 设置路由
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PERMISSION: (state, permission) => {
    state.permission = permission
  }
}

const actions = {
  // 动态添加路由
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // let accessedRoutes
      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      // commit('SET_ROUTES', accessedRoutes)
      // resolve(accessedRoutes)
      // console.log(roles, 'xxxxxxxxxxxxxxxx');

      // 判断一下 如果是 roleCode === SUPERADMIN 就传 roleCode不然就传id
      let roleCode
      if (roles.roleCode === 'SUPERADMIN') {
        roleCode = roles.roleCode
      } else {
        roleCode = roles.id

      }
      // 这里去请求角色得权限
      getRoles(roleCode).then(res => {
        // console.log(res.data.list, 'xxxxxxxxxxxxxxxx');
        // 获取到数据之前去做动态路由渲染 把后端返回得数据 转换成路由得格式
        // generateRoutes在utils得 index中
        let routerss = generateRoutes(res.data.list)
        // console.log(routerss, '转换之后得路由');

        // 发起请求用户权限的一个请求
        getPermissions(roleCode).then(res => {
          console.log(res, '权限信息');
          // 放到权限中
          commit('SET_PERMISSION', res.data.list)

        })
        commit('SET_ROUTES', routerss)
        resolve(routerss)
        // resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
